<template>
  <div class="post-list-page">
    <div class="page-header">
      <div class="header-content">
        <h1>帖子广场</h1>
        <el-button type="primary" @click="$router.push('/posts/create')" v-if="isAuthenticated">
          <el-icon><EditPen /></el-icon>
          发布帖子
        </el-button>
      </div>
    </div>

    <div class="page-content">
      <div class="filter-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索帖子..."
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select v-model="selectedCategory" placeholder="选择分类" clearable>
          <el-option label="全部分类" value="" />
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>

        <el-select v-model="sortBy" placeholder="排序方式">
          <el-option label="最新发布" value="createTime" />
          <el-option label="最多浏览" value="viewCount" />
          <el-option label="最多点赞" value="likeCount" />
        </el-select>
      </div>

      <div class="post-list" v-loading="loading">
        <div v-if="posts.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无帖子" />
        </div>

        <div v-for="post in posts" :key="post.id" class="post-item" @click="goToPost(post.id)">
          <div class="post-meta">
            <el-tag v-if="post.isTop" type="danger" size="small">置顶</el-tag>
            <el-tag v-if="post.category" type="primary" size="small">{{
              post.category.name
            }}</el-tag>
          </div>

          <h3 class="post-title">{{ post.title }}</h3>

          <p class="post-excerpt" v-html="getPostExcerpt(post)"></p>

          <div class="post-stats">
            <div class="author-info">
              <el-avatar :size="24" :src="post.author?.avatar">
                {{ post.author?.username?.charAt(0) }}
              </el-avatar>
              <span class="author-name">{{ post.author?.username }}</span>
            </div>

            <div class="stats">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ post.viewCount }}
              </span>
              <span class="stat-item">
                <el-icon><Star /></el-icon>
                {{ post.likeCount }}
              </span>
              <span class="stat-item">
                <el-icon><ChatDotRound /></el-icon>
                {{ post.commentCount }}
              </span>
              <span class="create-time">{{ formatTime(post.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onActivated } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { EditPen, Search, View, Star, ChatDotRound } from "@element-plus/icons-vue";
import { isAuthenticated } from "@/utils/auth";
import { getPosts } from "@/api/posts";
import { getCategories } from "@/api/categories";
import type { Post, Category } from "@/types";

const router = useRouter();

// 响应式数据
const loading = ref(false);
const posts = ref<Post[]>([]);
const categories = ref<Category[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 筛选条件
const searchKeyword = ref("");
const selectedCategory = ref("");
const sortBy = ref("createTime");

// 加载帖子列表
const loadPosts = async () => {
  loading.value = true;
  try {
    const response = await getPosts({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value,
      categoryId: selectedCategory.value ? Number(selectedCategory.value) : undefined,
      sortBy: sortBy.value,
      sortOrder: "DESC",
    });

    // 转换数据格式以匹配前端类型
    posts.value = response.items.map((post: any) => ({
      id: post.id,
      title: post.title,
      content: post.content,
      excerpt: post.summary,
      viewCount: post.viewCount,
      likeCount: post.likeCount,
      commentCount: post.commentCount,
      isTop: post.isTop,
      createTime: post.createdAt,
      updateTime: post.updatedAt,
      author: post.author,
      category: post.category,
      userId: post.author?.id,
      categoryId: post.category?.id,
      status: post.status === 1 ? "published" : "draft",
    }));

    total.value = response.total;
    console.log("帖子列表加载成功:", posts.value);
  } catch (error) {
    console.error("Failed to load posts:", error);
    ElMessage.error("加载帖子列表失败");

    // 出错时显示空列表
    posts.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await getCategories();
    categories.value = response;
    console.log("分类列表加载成功:", categories.value);
  } catch (error) {
    console.error("Failed to load categories:", error);

    // 出错时使用空数组
    categories.value = [];
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadPosts();
};

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadPosts();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadPosts();
};

// 跳转到帖子详情
const goToPost = (postId: number) => {
  router.push(`/posts/${postId}`);
};

// 简单的Markdown渲染
const renderMarkdown = (content: string, isExcerpt = false) => {
  if (!content) return "";

  let html = content;

  // 如果是摘要，先截取内容
  if (isExcerpt) {
    html = html.substring(0, 200);
  }

  // 粗体和斜体
  html = html.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>");
  html = html.replace(/\*(.*?)\*/g, "<em>$1</em>");

  // 代码
  html = html.replace(/`([^`]*)`/g, "<code>$1</code>");

  // 移除标题标记（在摘要中不需要）
  if (isExcerpt) {
    html = html.replace(/^#{1,6}\s+/gm, "");
  }

  // 换行
  html = html.replace(/\n/g, "<br>");

  return html;
};

// 获取帖子摘要
const getPostExcerpt = (post: Post) => {
  const excerpt = post.excerpt || post.content;
  const renderedExcerpt = renderMarkdown(excerpt, true);
  return renderedExcerpt + (excerpt.length > 200 ? "..." : "");
};

// 格式化时间
const formatTime = (time: string) => {
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60));
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60));
      return minutes === 0 ? "刚刚" : `${minutes}分钟前`;
    }
    return `${hours}小时前`;
  } else if (days === 1) {
    return "昨天";
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return date.toLocaleDateString();
  }
};

// 监听筛选条件变化
watch([selectedCategory, sortBy], () => {
  currentPage.value = 1;
  loadPosts();
});

// 组件挂载
onMounted(() => {
  loadPosts();
  loadCategories();
});

// 组件激活时重新加载数据（当从其他页面返回时）
onActivated(() => {
  loadPosts();
});
</script>

<style scoped lang="scss">
.post-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;

  .page-header {
    background: white;
    padding: 20px 0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;

    .header-content {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h1 {
        margin: 0;
        color: #2c3e50;
        font-size: 28px;
      }
    }
  }

  .page-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;

    .filter-bar {
      display: flex;
      gap: 16px;
      margin-bottom: 20px;
      padding: 20px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

      .search-input {
        flex: 1;
        max-width: 300px;
      }

      .el-select {
        width: 150px;
      }
    }

    .post-list {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      min-height: 400px;

      .empty-state {
        padding: 60px 0;
      }

      .post-item {
        padding: 20px;
        border-bottom: 1px solid #ebeef5;
        cursor: pointer;
        transition: background-color 0.2s;

        &:hover {
          background-color: #f8f9fa;
        }

        &:last-child {
          border-bottom: none;
        }

        .post-meta {
          margin-bottom: 10px;

          .el-tag {
            margin-right: 8px;
          }
        }

        .post-title {
          font-size: 18px;
          font-weight: 600;
          color: #2c3e50;
          margin: 0 0 12px 0;
          line-height: 1.4;
        }

        .post-excerpt {
          color: #606266;
          font-size: 14px;
          line-height: 1.6;
          margin: 0 0 16px 0;

          :deep(strong) {
            font-weight: 600;
            color: #2c3e50;
          }

          :deep(em) {
            font-style: italic;
            color: #7f8c8d;
          }

          :deep(code) {
            background-color: #f8f9fa;
            color: #e96900;
            padding: 1px 4px;
            border-radius: 3px;
            font-family: "Monaco", "Consolas", "Courier New", monospace;
            font-size: 12px;
          }
        }

        .post-stats {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .author-info {
            display: flex;
            align-items: center;
            gap: 8px;

            .author-name {
              font-size: 14px;
              color: #909399;
            }
          }

          .stats {
            display: flex;
            align-items: center;
            gap: 16px;

            .stat-item {
              display: flex;
              align-items: center;
              gap: 4px;
              font-size: 14px;
              color: #909399;

              .el-icon {
                font-size: 16px;
              }
            }

            .create-time {
              font-size: 12px;
              color: #c0c4cc;
            }
          }
        }
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
      padding: 20px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .post-list-page {
    .page-header .header-content {
      flex-direction: column;
      gap: 16px;

      h1 {
        font-size: 24px;
      }
    }

    .page-content {
      padding: 0 10px;

      .filter-bar {
        flex-direction: column;

        .el-select {
          width: 100%;
        }
      }

      .post-list .post-item {
        padding: 16px;

        .post-stats {
          flex-direction: column;
          align-items: flex-start;
          gap: 12px;

          .stats {
            gap: 12px;
          }
        }
      }
    }
  }
}
</style>
